package ai.peanut.selfbase.modules.user.service.impl;

import ai.peanut.selfbase.common.constants.GlobalConstant;
import ai.peanut.selfbase.common.domain.DataResult;
import ai.peanut.selfbase.common.enums.ResultTypeEnum;
import ai.peanut.selfbase.common.security.shiro.ShiroUtils;
import ai.peanut.selfbase.common.utils.UserUtils;
import ai.peanut.selfbase.modules.sys.entity.UserRole;
import ai.peanut.selfbase.modules.sys.service.IUserRoleService;
import ai.peanut.selfbase.modules.user.dao.UserMapper;
import ai.peanut.selfbase.modules.user.entity.User;
import ai.peanut.selfbase.modules.user.pojo.UserDto;
import ai.peanut.selfbase.modules.user.pojo.UserParam;
import ai.peanut.selfbase.modules.user.service.IUserService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lichong
 * @since 2019-02-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IUserRoleService userRoleService ;
    /**
     * 获取列表
     * @param
     * @param params
     * @return
     */
    @Override
    public Page<UserDto> selectAllPageByParams(UserParam params ) {
        Page page = new Page(params.getCurrent()==null?1:params.getCurrent(),
                params.getSize()==null? GlobalConstant.WEB_PAGE_NUMBER:params.getSize());

        List<UserDto> list = baseMapper.selectAllByParams(page,params) ;
        page.setRecords(list) ;
        return  page ;
    }


    /**
     * 批量删除
     * @param params
     * @return
     */
    @Override
    public  int deleteByIds( UserParam params) {
        return baseMapper.deleteByIds(params) ;
    }


    @Override
    public DataResult updatePassword(UserParam userParam){
        UserDto dto = UserUtils.getCurrentUser() ;
        String newPassword = userParam.getNewPassword();
        String newPasswordRepeat = userParam.getNewPasswordRepeat();
        if( !newPassword.equals( newPasswordRepeat ) ){
            return DataResult.faild(ResultTypeEnum.PASSWORD_NOT_SAME.getCode(),
                    ResultTypeEnum.PASSWORD_NOT_SAME.getMessage());
        }
        User user  = this.selectById(dto.getId()) ;

        String validatePassword = ShiroUtils.generatorMd5( userParam.getPassword(),
                ShiroUtils.generatorSale(user.getLoginName() ,user.getId().toString(), user.getSalt() )) ;
        if(!validatePassword.equals(user.getPassword())){
            return DataResult.faild(ResultTypeEnum.INCORRECTCREDENTIALS.getCode(),
                    ResultTypeEnum.INCORRECTCREDENTIALS.getMessage());
        }

        User updateUser = new User() ;
        updateUser.setId( user.getId() ) ;
        String randomSalt = ShiroUtils.generatorRandom() ;
        String password = ShiroUtils.generatorMd5( newPassword,
                ShiroUtils.generatorSale(user.getLoginName() ,user.getId().toString(), randomSalt )) ;
        updateUser.setSalt( randomSalt ) ;
        updateUser.setPassword(password);

        updateUser.setUpdateTime(new Date());
        this.updateById(updateUser);
        return DataResult.success();

    }


    @Override
    public DataResult<Boolean> updateUser(UserParam params){

        Date now = new Date() ;
        User user = new User() ;
        BeanUtils.copyProperties(params,user);
        Long userId = UserUtils.getCurrentUser().getId() ;
        user.setUpdateUserId(userId);
        user.setUpdateTime(now);
        user.setCreateTime(null);
        user.setCreateUserId(null);
        user.setLoginName(null);
        user.setPassword(null);
        user.setSalt(null);
        this.updateById(user);
        userRoleService.deleteByUserId(user.getId());
        this.insertUserRole(user.getId() , params.getRoleIdList()) ;
        return DataResult.success() ;
    }
    /**
     * 新增用户
     * @param params
     * @return
     */
    @Override
    public DataResult<Boolean> insertUser(UserParam params){
        Date now = new Date() ;
        User user = new User() ;
        BeanUtils.copyProperties(params,user);
        Long userId = UserUtils.getCurrentUser().getId() ;
        user.setCreateUserId(userId);
        user.setUpdateUserId(userId);
        user.setCreateTime(now);
        user.setUpdateTime(now);
        if(user.getDelFlag()==null){
            user.setDelFlag(1);
        }

        String randomStr = ShiroUtils.generatorRandom() ;
        user.setSalt( randomStr ) ;
        user.setPassword("1");
        baseMapper.insertAllColumn(user);
        String realsalt = ShiroUtils.generatorSale(user.getLoginName(),user.getId().toString(),randomStr) ;
        User userUpdate = new User() ;
        userUpdate.setPassword(ShiroUtils.generatorMd5("000000",realsalt));
        userUpdate.setId(user.getId());
        baseMapper.updateById(userUpdate);

        this.insertUserRole(user.getId() , params.getRoleIdList()) ;

        return DataResult.success() ;
    }


    private void insertUserRole(Long userId ,  List<Long> roleIdList){
   
        if( roleIdList != null && roleIdList.size() > 0 ){
            for(Long id : roleIdList ){
                UserRole userRole = new UserRole() ;
                userRole.setRoleId(id);
                userRole.setUserId(userId);
                userRoleService.insertAllColumn(userRole);
            }

        }
    }
@Override
    public UserDto getUserByLoginName(String loginName) {
        return baseMapper.getUserByLoginName( loginName ) ;
    }
}
